package org.hzs.web_client.servlet;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.hzs.logging.error;

public class 业务 extends __ implements com.sun.net.httpserver.HttpHandler {

    public 业务(final int ci端口_i, final org.hzs.logging.error ci_error) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException {
        super(ci端口_i, ci_error);
        d资源缓冲 = new java.util.TreeMap<String, byte[]>();
        d资源缓冲.put("/index.html", ("<!DOCTYPE HTML><HTML><HEAD><TITLE>正在登入，请耐心等待......</TITLE><META http-equiv=Content-Type content='text/html; charset=UTF-8'></HEAD><BODY><DIV style='text-align:center;'><BR><BR>正在登入，请耐心等待。。。。。。<BR><BR><IMG src=''/><BR></DIV></BODY></HTML>").getBytes("UTF-8"));
    }

    /**
     * 下载所需资源，已下载但未改变的资源不再下载
     */
    public void g置业务模块() throws error, MalformedURLException, IOException {
        d资源缓冲.clear();
        //取得可下载资源
        String ji_s = org.hzs.web_client.Property.applet.g会晤服务器("{指令0:'资源'}", "{}");
        org.hzs.json.JSONObject ji2_JSON = org.hzs.json.JSONObject.d副本();
        ji2_JSON.set(ji_s, null);
        //搭建可能需下载资源
        java.io.File file = null;
        java.io.FileInputStream in = null;
        Object key = null;
        org.hzs.json.JSONObject ji1_JSON = org.hzs.json.JSONObject.d副本();
        Iterator keys = ji2_JSON.keys();
        while (keys.hasNext()) {
            key = keys.next();
            file = new java.io.File(org.hzs.web_client.Property.i工作路径_s + key);
            if (!file.exists()) {
                continue;
            }
            byte[] byt = new byte[(int) file.length()];
            try {
                in = new java.io.FileInputStream(file);
                in.read(byt);
                byt = org.hzs.安全.DIGEST.i摘要_byteArray(byt, org.hzs.安全.DIGEST.SHA_512);
                ji1_JSON.put((String) key, new String(org.hzs.编码.Base64.i编码_byteArray(byt), "UTF-8"));
            } catch (FileNotFoundException ex) {
            } catch (IOException | NoSuchAlgorithmException ex) {
            }
        }
        //再次取得可下载资源
        ji_s = org.hzs.web_client.Property.applet.g会晤服务器("{指令0:'资源'}", ji1_JSON.toString(null));
        ji1_JSON.set(ji_s, null);
        //开始下载资源
        keys = ji1_JSON.keys();
        while (keys.hasNext()) {
            key = keys.next();
            ji_s = ji1_JSON.getString((String) key, null);
            URL url = new URL(ji_s);
            URLConnection conn = url.openConnection();
            InputStream inStream = conn.getInputStream();
            FileOutputStream fs = new FileOutputStream(org.hzs.web_client.Property.i工作路径_s + key);
            byte[] buffer = new byte[1204];
            int byteread;
            while ((byteread = inStream.read(buffer)) != -1) {
                fs.write(buffer, 0, byteread);
            }
            fs.flush();
            fs.close();
            fs = null;
            inStream.close();
        }
        //开始缓冲资源
        keys = ji2_JSON.keys();
        while (keys.hasNext()) {
            g缓冲资源((String) keys.next());
        }
    }

    public void g失败() {
        try {
            org.hzs.web_client.Property.frame.setResizable(false);
            d资源缓冲.clear();
            d资源缓冲.put("/index.html", "<!DOCTYPE HTML><HTML><HEAD><TITLE>温馨提示</TITLE><META http-equiv=Content-Type content='text/html; charset=UTF-8'></HEAD><BODY><TABLE height='100%' cellSpacing=0 cellPadding=0 width='100%' border=0><TBODY><TR><TD><TABLE height=422 cellSpacing=0 cellPadding=0 width=382 align=center border=0><TBODY><TR><TD background=''><TABLE cellSpacing=0 cellPadding=0 width='100%' align=center border=0><TBODY><TR><TD style='PADDING-RIGHT: 20px; PADDING-LEFT: 180px; PADDING-BOTTOM: 30px; PADDING-TOP: 80px'>由于网站管理员的鸡鸡丢失，导致了本页面不能访问了，实在抱歉啊。</TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE></BODY><p align='center'>今天不聊天：身为站长，终日劳累，前途迷茫；三更睡，五更起<br>大米咸菜，小板木床；世人费解，屡失她爱，立足新疆，奋发图强</SPAN><br>Copyright &copy 2005-2010, <A href='http://960wcn.blog.163.com/'>960wcn.blog.163.com</A>. All rights reserved.<SCRIPT>applet.g禁止改变窗口大小();applet.g蜂鸣();</SCRIPT></BODY></HTML>".getBytes("UTF-8"));
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(业务.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
        }
    }

    @Override
    public void handle(final com.sun.net.httpserver.HttpExchange he) throws IOException {
        // <editor-fold defaultstate="collapsed" desc="自用">
        class 自用 implements Cloneable {

            java.io.OutputStream out = null;
            String i路径_s = null, i入站网址_s = null, i浏览器_s = null;
            byte[] i缓冲 = null;
            org.hzs.json.JSONObject i_JSON = null;
            String i_s = null;
//            String $ = null, _ = null;

            自用 d副本() throws CloneNotSupportedException {
                return (自用) super.clone();
            }

            void close() {
                i_JSON = null;
                i_s = null;
                i缓冲 = null;
                i路径_s = null;
                i入站网址_s = null;
                i浏览器_s = null;
                if (out != null) {
                    try {
                        out.flush();
                        out.close();
                    } catch (IOException ex) {
                    }
                    out = null;
                }
            }
        }// </editor-fold>
        自用 ji自用 = null;
        try {
            // <editor-fold defaultstate="collapsed" desc="利用对象复制初始化过程内部变量">
            ji自用 = (自用) org.hzs.web_client.Property.d对象池.get(自用.class.getName());
            if (ji自用 == null) {
                ji自用 = new 自用();
                org.hzs.web_client.Property.d对象池.put(自用.class.getName(), ji自用);
            }
            ji自用 = ji自用.d副本();
            // </editor-fold>
            he.sendResponseHeaders(200, 0);
            ji自用.i入站网址_s = he.getRemoteAddress().getHostName();
            if (ji自用.i入站网址_s != null && !ji自用.i入站网址_s.equals("localhost") && !ji自用.i入站网址_s.equals("127.0.0.1")) {
                return;
            }
            ji自用.i浏览器_s = he.getRequestHeaders().get("User-Agent").get(0); //得到浏览器等相关信息
            if (!ji自用.i浏览器_s.contains(" JavaFX/")) {//确保用的是自制浏览器     //"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.14 (KHTML, like Gecko) JavaFX/2.2 Safari/535.14" 
                return;
            }
            //取得客户访问的资源
            //路径 ＝ 上下文路径 + 文档路径
            ji自用.i路径_s = java.net.URLDecoder.decode(he.getRequestURI().getRawPath(), "UTF-8");//解析出错抛出错误，并返回客户端，不影响程序运行
            if (ji自用.i路径_s.equals("/")) {
                ji自用.i路径_s = ji自用.i路径_s + "index.html";
            }
            ji自用.i路径_s = ji自用.i路径_s.replaceAll("//", "/");
            ji自用.i缓冲 = d资源缓冲.get(ji自用.i路径_s);
//            if (ji自用.i缓冲 == null) {//缓冲不存在数据，转向服务器索取
//                ji自用.$ = request.getParameter("$");
//                ji自用._ = request.getParameter("_");
//                if (ji自用.$ == null || ji自用._ == null) {
//                    return;
//                }
//                ji自用.i_s = org.hzs.web_client.Property.applet.g会晤服务器(ji自用.$, request.getParameter("_"));
//                ji自用.i_JSON = org.hzs.json.JSONObject.d副本();
//                ji自用.i_JSON.set(ji自用.i_s, null);
//                if (!Boolean.TRUE.equals(ji自用.i_JSON.getBoolean("success", null))) {
//                    return;
//                }
//                ji自用.i缓冲 = ji自用.i_JSON.getString("_", null).getBytes("UTF-8");
//            }
            he.getResponseHeaders().set("Content-Type", "text/html;charset=UTF-8");
            ji自用.out = he.getResponseBody();
            ji自用.out.write(ji自用.i缓冲);
        } catch (CloneNotSupportedException ex) {
            Logger.getLogger(业务.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (ji自用 != null) {
                ji自用.close();
                ji自用 = null;
            }
            he.close();
        }
    }
}
